﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraLayout;
using PRO_DOCS.DAL.Database;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.Dashboard
{
    public partial class UserActivityAmount : PRO_DOCS.BLL.WIN.Templates.DevxPermissionUserControlTemplate
    {
        private IBindingList _source;

        public UserActivityAmount()
        {
            InitializeComponent();
        }
        #region EXPORT CHART

        private void tsbExportImg_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "Jpeg file | *.jpeg";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                chartControl1.ExportToImage(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

        }

        private void tsbExportPDF_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "Pdf file | *.pdf";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                DevExpress.XtraPrinting.PdfExportOptions PdfExportOptions = new DevExpress.XtraPrinting.PdfExportOptions();
                PdfExportOptions.Compressed = false;
                PdfExportOptions.ConvertImagesToJpeg = true;
                PdfExportOptions.DocumentOptions.Author = "ECHO";
                PdfExportOptions.DocumentOptions.Subject = "User Activity Amount report";
                PdfExportOptions.ImageQuality = DevExpress.XtraPrinting.PdfJpegImageQuality.Highest;
                chartControl1.ExportToPdf(sfd.FileName, PdfExportOptions);
            }
        }

        private void tsbExportXLSX_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "Excel file | *.xlsx";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                DevExpress.XtraPrinting.XlsxExportOptions xlsxExportOptions = new DevExpress.XtraPrinting.XlsxExportOptions();
                xlsxExportOptions.ExportMode = DevExpress.XtraPrinting.XlsxExportMode.SingleFile;
                xlsxExportOptions.SheetName = "UAA " + DateTime.Now.ToString("dd.MM.yyyy");
                xlsxExportOptions.ExportHyperlinks = true;
                xlsxExportOptions.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Text;
                chartControl1.ExportToXlsx(sfd.FileName, xlsxExportOptions);
            }
        }

        private void tsbExportRTF_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter = "RFT file | *.rtf";
            sfd.Title = "Select Saving Directory";
            if (sfd.ShowDialog().Equals(DialogResult.OK))
            {
                chartControl1.ExportToRtf(sfd.FileName);
            }
        }
        #endregion
        private delegate BindingList<KeyValuePair<string, decimal>> FlusherGetArchivee(DateTime from, DateTime to);
        private void LoadUsersState(IAsyncResult result)
        {
            var flusher = (FlusherGetArchivee)result.AsyncState;
            var res = flusher.EndInvoke(result);
            chartControl1.BeginInvoke(new Action(delegate
                                                     {
                                                         _source = res;
                                                         chartControl1.DataSource = _source;
                                                         chartControl1.Series[0].ArgumentDataMember = "Key";
                                                         chartControl1.Series[0].ValueDataMembers.AddRange("Value");
                                                     }));
        }

        private BindingList<KeyValuePair<string, decimal>> GetUsersState(DateTime from, DateTime to)
        {
            try
            {
                this.BeginInvoke(new Action(() => AddLegend(from, to)));

                var list =
                    PRO_DOCSDatabaseDataContext.getAllUserActivityAmount(from, to).ToList().Where(
                        m => m.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE.HasValue).GroupBy(
                            m => m.ARCHIVE_DEPARTMENT_NAME).Select(
                                m =>
                                new KeyValuePair<string, decimal>(m.Key,
                                                                  Math.Round(m.Sum(
                                                                      s =>
                                                                      s.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE.Value) /
                                                                             1024, 2)))
                        .ToList();
                var ctx =
                    new PRO_DOCS.DAL.Database.PRO_DOCSDatabaseDataContext(
                        BLL.WIN.Properties.Settings.Default.PRO_DOCSConnectionString);
                var temp = ctx.ARCHIVE_DEPARTMENTs.ToList().Select(m => m.ARCHIVE_DEPARTMENT_NAME).Where(
                    m => !list.Any(s => s.Key == m.ToString())).ToList();
                list.AddRange(temp.Select(m => new KeyValuePair<string, decimal>(m.ToString(), 0)));
                return new BindingList<KeyValuePair<string, decimal>>(list);
            }
            catch (Exception)
            {
                return null;
            }
        }


        private void UserActivityAmount_Load(object sender, EventArgs e)
        {
            _source = new BindingList<KeyValuePair<string, int>>();
            fromDateEdit.DateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            toDateEdit.DateTime = DateTime.Now;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (_source != null)
                _source.Clear();
            dxErrorProvider1.ClearErrors();
            if (fromDateEdit.DateTime != new DateTime())
            {
                if (toDateEdit.DateTime != new DateTime())
                {
                    var flusher = new FlusherGetArchivee(GetUsersState);
                    flusher.BeginInvoke(fromDateEdit.DateTime, toDateEdit.DateTime, LoadUsersState, flusher);
                }
                else
                {
                    dxErrorProvider1.SetError(toDateEdit, "Enter a valida data");
                }
            }
            else
            {
                dxErrorProvider1.SetError(fromDateEdit, "Enter a valida data");
            }
        }

        private void AddLegend(DateTime from, DateTime to)
        {
            //layoutControl2.Controls.Clear();

            var list =
                PRO_DOCSDatabaseDataContext.getAllUserActivityAmount(from, to).ToList().Where(
                    m => m.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE.HasValue).GroupBy(m => m.ARCHIVE_DEPARTMENT_NAME).
                    Select(m => new KeyValuePair<string, decimal>(m.Key, m.Count())).ToList();
            var ctx =
                    new PRO_DOCS.DAL.Database.PRO_DOCSDatabaseDataContext(
                        BLL.WIN.Properties.Settings.Default.PRO_DOCSConnectionString);
            var temp = ctx.ARCHIVE_DEPARTMENTs.ToList().Select(m => m.ARCHIVE_DEPARTMENT_NAME).Where(
                m => !list.Any(s => s.Key == m.ToString())).ToList();
            list.AddRange(temp.Select(m => new KeyValuePair<string, decimal>(m.ToString(), 0)));
            foreach (KeyValuePair<string, decimal> pair in list)
            {
                var layCtrl1 = new LayoutControlItem(layoutControl2.Root);
                var lbl1 = new DevExpress.XtraEditors.LabelControl();

                //lbl1.Appearance.BackColor = System.Drawing.Color.Green;
                //lbl1.Location = new System.Drawing.Point(list.IndexOf(pair) * 20, 0);
                //lbl1.Name = Guid.NewGuid().ToString();
                //lbl1.Size = new System.Drawing.Size(6, 21);
                //lbl1.StyleController = this.layoutControl2;
                //lbl1.TabIndex = 5;
                //lbl1.Text = "  ";

                layCtrl1.Control = lbl1;
                layCtrl1.CustomizationFormText = "layoutControlItem7" + list.IndexOf(pair);
                layCtrl1.Location = new System.Drawing.Point(list.IndexOf(pair) * 20, 0);
                layCtrl1.Name = Guid.NewGuid().ToString();
                layCtrl1.Size = new System.Drawing.Size(6, 21);
                layCtrl1.Text = "layoutControlItem7";
                layCtrl1.TextSize = new System.Drawing.Size(0, 0);
                layCtrl1.TextToControlDistance = 0;
                layCtrl1.TextVisible = false;


                //////////////////////////
                var layCtrl2 = new LayoutControlItem(layoutControl2.Root);
                var lbl2 = new DevExpress.XtraEditors.LabelControl();
                lbl2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                       | System.Windows.Forms.AnchorStyles.Left)
                       | System.Windows.Forms.AnchorStyles.Right)));
                lbl2.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
                lbl2.Location = new System.Drawing.Point(10, list.IndexOf(pair) * 20);
                lbl2.Name = Guid.NewGuid().ToString();
                lbl2.Size = new System.Drawing.Size(170, 17);
                lbl2.StyleController = this.layoutControl2;
                lbl2.TabIndex = 6;
                lbl2.Text = string.Format("{0}:{1}", pair.Key, pair.Value);
                // 
                // layoutControlItem8
                // 
                layCtrl2.Control = lbl2;
                layCtrl2.CustomizationFormText = "layoutControlItem8" + list.IndexOf(pair);
                layCtrl2.Location = new System.Drawing.Point(10, list.IndexOf(pair) * 20);
                layCtrl2.Name = Guid.NewGuid().ToString();
                layCtrl2.Size = new System.Drawing.Size(170, 17);
                layCtrl2.Text = "layoutControlItem8";
                layCtrl2.TextSize = new System.Drawing.Size(170, 19);
                layCtrl2.TextToControlDistance = 0;
                layCtrl2.TextVisible = false;


                this.Root.Items.AddRange(new BaseLayoutItem[] { layCtrl1, layCtrl2 });
            }


            var empty = new EmptySpaceItem(layoutControl2.Root)
                            {
                                AllowHotTrack = false,
                                CustomizationFormText = "emptySpaceItem1",
                                Location = new System.Drawing.Point(0, list.Count * 20),
                                Name = Guid.NewGuid().ToString(),
                                Size = new System.Drawing.Size(500, 306),
                                Text = "emptySpaceItem1",
                                TextSize = new System.Drawing.Size(0, 0)
                            };

            this.Root.Items.AddRange(new BaseLayoutItem[] { empty });
        }
    }
}